package com.yami.controller

import org.springframework.stereotype.Controller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod._
import org.springframework.web.servlet.ModelAndView
import dispatch._
import scala.xml.Node
import com.yami.repository.ArtistDb
import com.yami.domain.Artist

/**
 *
 * @ author caibosi
 * @ created 2014-08-07
 *
 */
@Controller
class ArtistController {

  @Autowired
  val db: ArtistDb = null

  @RequestMapping(value = Array("/artists"),method = Array(GET))
  def loadArtists() = new ModelAndView("artists","topArtists",db.findAll)

  @RequestMapping(value = Array("/refresh"),method = Array(GET))
  def refresh() = {
    retrieveAndLoadArtists()
    new ModelAndView("artists","topArtists",db.findAll)
  }

  private def retrieveAndLoadArtists(){
    val rootUrl = "http://ws.audioscrobbler.com/2.0/"
    val apiMethod = "chart.gettopartists"
    val apiKey = "9ab62711de30e0760c8558ad9a3f53a7"
    val req = url(rootUrl + "?method=" + apiMethod + "&api_key=" + apiKey)
    Http(req OK as.xml.Elem).map{resp =>
      val artists = resp \\ "artist"
      artists.foreach{ node =>
          val artist = makeArtist(node)
          println(artist.name)
          db.save(artist)
      }
    }()
  }

  private def makeArtist(n:Node) = {
    val name = (n \ "name").text
    val playCount = (n \ "playcount").text.toLong
    val listeners = (n \ "listeners").text.toLong
    Artist(name = name,playCount = playCount,listeners = listeners)
  }

}
